package cn.codewen.service.impl;

import cn.codewen.service.CosService;
import cn.codewen.service.UserService;
import cn.codewen.utils.CosUtils;
import com.qcloud.cos.model.COSObjectSummary;

import java.util.ArrayList;
import java.util.List;

public class CosServiceImpl implements CosService {
    @Override
    public List listObjects(String prefix) {

        //1. 创建cosUtils对象
        CosUtils cosUtils = new CosUtils();

        //2. 调用列文件和目录的方法
        List<COSObjectSummary> cosObjectSummaries = cosUtils.listObjects(prefix);

        //3. 定义2个变量
        ArrayList<COSObjectSummary> dirs = new ArrayList<>();
        ArrayList<COSObjectSummary> files = new ArrayList<>();

        //4. 遍历
        for (COSObjectSummary cosObjectSummary : cosObjectSummaries) {
           /*
           cloud01/
                    0
           -----------------------
                    cloud01/test/
                    0
           -----------------------
           -----------------------
                    cloud01/test/12222/
                            0
             -----------------------
             -----------------------
                            cloud01/test/1223/
                            0

*/

            String newDir = cosObjectSummary.getKey().replace(prefix, "");
            //prefix====>cloud01/
            // cloud01/  ======>""                 0      NO
            // cloud01/test/ ====>  test/          0      OK
            // cloud01/test/12222/=====> test/12222/   0  NO
            // cloud01/codewen.jpg   =====> codewenwen.jpg    >0   OK
            // cloud01/test/codewen1.jpg  ======> test/codewen1.jpg   >0  NO

            // 算出/的次数
            int count = newDir.length() - newDir.replace("/", "").length();

            if (cosObjectSummary.getSize() == 0 && count == 1) {

                System.out.println(cosObjectSummary.getKey());
                dirs.add(cosObjectSummary);
            }

            if (cosObjectSummary.getSize() > 0 && count == 0) {
                System.out.println(cosObjectSummary.getKey());
                files.add(cosObjectSummary);
            }


        }
        dirs.addAll(files);

        return dirs;
    }

    @Override
    public Boolean addDirs(String key) {

        CosUtils cosUtils = new CosUtils();
        String s = cosUtils.addDirs(key);
        if (s != null) {
            return true;
        } else {
            return false;
        }
    }
}
